package com.xinyue.cross.server.client;

import com.xinyue.cross.server.client.model.GameServerConnectionModel;
import com.xinyue.game.message.GameServerMessageModel;
import com.xinyue.game.message.GameServerRequestHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class GameServerClientService {
    private Logger logger = LoggerFactory.getLogger(GameServerClientService.class);
    @Autowired
    private GameServerBalanceService gameServerBalanceService;

    public void sendMsg(String userKey, String serviceId, GameServerMessageModel<GameServerRequestHeader> msgModel) throws NotFundGameServerException {
        GameServerConnectionModel gameServerConnectionModel = gameServerBalanceService.selectNettyClientService(serviceId, userKey);
        if (gameServerConnectionModel == null) {
            logger.info("当前服务不存在，可能是未注册，userKey: {}, serviceId: {}", userKey, serviceId);
            throw new NotFundGameServerException(String.format("当前服务不存在，可能是未注册，serviceId: %s", serviceId));
        }
        NettyClientService nettyClientService = gameServerConnectionModel.getNettyClientService();
        if (nettyClientService.isConnected()) {
            nettyClientService.sendMessage(msgModel);
        } else {
            logger.info("当前服务连接已断开，发送消息失败,serviceId: {}, header: {}", serviceId, msgModel.getHeader());
        }
    }

    public String getServiceIdFromRequestUri(String requestUri) throws GameServerRequestUriErrorException {
        String[] pathFields = requestUri.split("/");
        if (pathFields.length < 2) {
            logger.info("请求路径错误，请求路径一般至少由两部分/组成，当前是： {}", requestUri);
            throw new GameServerRequestUriErrorException("请求路径错误，requestUri: " + requestUri);
        }
        return pathFields[1];
    }
}
